const fs = require('fs');
const path = require('path');
const parser = require('@babel/parser');

// 读取命令行传入的文件路径
const filePath = process.argv[2];
if (!filePath) {
    console.error('Usage: node count_functions.js <path_to_js_file>');
    process.exit(1);
}

// 读取文件内容
const code = fs.readFileSync(filePath, 'utf-8');

// 解析代码生成AST
const ast = parser.parse(code, {
    sourceType: 'module', // 默认值，也可以设置为 'script'
    plugins: ['jsx'] // 如果需要解析 JSX
});

// 统计函数
function countFunctions(ast) {
    let arrowFunctions = 0;
    let anonymousFunctions = 0;

    function traverse(node) {
        if (node.type === 'ArrowFunctionExpression') {
            arrowFunctions++;
        } else if (node.type === 'FunctionExpression' && !node.id) {
            anonymousFunctions++;
        }

        for (const key in node) {
            if (node[key] && typeof node[key] === 'object') {
                traverse(node[key]);
            } else if (Array.isArray(node[key])) {
                node[key].forEach(child => {
                    if (child && typeof child === 'object') {
                        traverse(child);
                    }
                });
            }
        }
    }

    traverse(ast);
    return { arrowFunctions, anonymousFunctions };
}

// 统计结果
const { arrowFunctions, anonymousFunctions } = countFunctions(ast);

// 输出结果
console.log(`ArrowFunctionExpression count: ${arrowFunctions}`);
console.log(`Anonymous FunctionExpression count: ${anonymousFunctions}`);
